//
//  CYCycleScroll.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/7/12.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "HYCycleScroll.h"
#define titlelblH 40
@interface HYCycleScroll ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@end

@implementation HYCycleScroll
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
    }
    return self;
}

- (UICollectionViewFlowLayout *)layout
{
    if (!_layout)
    {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumLineSpacing = 0;
        _layout.itemSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _layout;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.pagingEnabled = YES;
        [self addSubview:_collectionView];
    }
    return _collectionView;
}

- (UIPageControl *)pageControl
{
    if (!_pageControl)
    {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.bounds.size.height - titlelblH, self.bounds.size.height - titlelblH, titlelblH, titlelblH)];
        _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.currentPageIndicatorTintColor = THEME_COLOR;
        [self addSubview:_pageControl];
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).with.offset(-GAP);
            make.bottom.equalTo(self);
        }];
    }
    return _pageControl;
}

- (void)setTopGames:(NSMutableArray <HYTopGameModel *> *)topGames
{
    if (_topGames != topGames)
    {
        _topGames = [NSMutableArray arrayWithArray:topGames];
        if ([_topGames count] > 1)
        {
            [_topGames addObject:topGames.firstObject];
            [_topGames insertObject:topGames.lastObject atIndex:0];
        }

        //防止循环图片无限网络请求url，禁止collectionview复用cell
        for (int i = 0; i < _topGames.count; i++)
        {
            NSString *cellid = [NSString stringWithFormat:@"HYCycleScrollCell%d",i];
            [self.collectionView registerClass:[HYCycleScrollCell class] forCellWithReuseIdentifier:cellid];
        }
        
        [self.collectionView reloadData];
        self.pageControl.numberOfPages = topGames.count;
        [self.timer setFireDate:[NSDate distantPast]];//开始

    }
}

- (NSTimer *)timer
{
    if (!_timer)
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
    return _timer;
}

- (void)updateTime
{
    CGFloat offSetX = _collectionView.contentOffset.x;//获取当前滚动视图的contentOffSet的x值
    offSetX += _collectionView.bounds.size.width;//让scrollView向右滚动一个屏幕宽的距离
    [_collectionView setContentOffset:CGPointMake(offSetX, 0) animated:YES];//开始偏移并伴有动画效果
}

#pragma mark - CollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.topGames.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellid = [NSString stringWithFormat:@"HYCycleScrollCell%ld",indexPath.row];
    HYCycleScrollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
    cell.model = self.topGames[indexPath.row];
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x/scrollView.bounds.size.width;
    if (page == 0)
    {//滚动到最左边
        [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width * (self.topGames.count - 2), 0) animated:NO];
        return;
    }
    else if (page == self.topGames.count - 1){//滚动到最右边
        [scrollView setContentOffset:CGPointMake(scrollView.bounds.size.width, 0) animated:NO];
        return;
    }
    _pageControl.currentPage = page - 1;
}

//拖拽scrollview的时候，暂停定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.timer invalidate];//取消计时器
    self.timer = nil;
}

//拖拽完成，减速过程完成，重启定时器
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    WS(self)
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t) 1.0 *NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        if (!weakSelf.timer)
            [weakSelf.timer setFireDate:[NSDate distantPast]];
    });
}

@end


//==============================================HYCycleScrollCell==============================================
@interface HYCycleScrollCell()
@property (nonatomic, strong) UIImageView *img;
@property (nonatomic, strong) UILabel *titleLBL;
@end
@implementation HYCycleScrollCell
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.img.hidden = NO;
    }
    return self;
}

- (UIImageView *)img
{
    if (!_img)
    {
       _img = [[UIImageView alloc] init];
        [self addSubview:_img];
        [_img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _img;
}

- (UILabel *)titleLBL
{
    if (!_titleLBL)
    {
         _titleLBL = [[UILabel alloc] init];
        _titleLBL.alpha = 0.8;
        _titleLBL.backgroundColor = [UIColor blackColor];
        _titleLBL.textColor = [UIColor whiteColor];
        _titleLBL.textAlignment = NSTextAlignmentLeft;
        _titleLBL.font = [UIFont systemFontOfSize:DefaultFont];
        [self addSubview:_titleLBL];
        [_titleLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self);
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.height.mas_equalTo(titlelblH);
        }];
    }
    return _titleLBL;
}

- (void)setModel:(HYTopGameModel *)model
{
    if (_model != model)
    {
        _model = model;
        self.titleLBL.text = model.title;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSString *url_string = self.model.img;
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_string]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
              self.img.image = [UIImage imageWithData:data];
            });
        });
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [CCNotice post:CCNoticeNameCycleScrollClick obj:nil info:@{@"gameid":self.model.gameid}];
}
@end
